package com.dfwl.packageio;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dfwl.packageio.core.base.BaseActivity;
import com.dfwl.packageio.core.bean.BarCodeInfo;
import com.dfwl.packageio.core.components.NiftyDialogComponents;
import com.dfwl.packageio.core.db.BarCodeDao;
import com.dfwl.packageio.core.excel.ExcelUtils;
import com.dfwl.packageio.moudle.PackageIoAdapter;
import com.dfwl.packageio.moudle.ScanActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auth &{zhujiule}
 * @date 2018/8/13
 * @copyright
 **/

public class MainActivity extends BaseActivity implements PackageIoAdapter.PackageIoListener{


   private static final int ZXING_CAMERA_PERMISSION = 1;
   private static final int ZXING_CAMERA_REQUESTCODE = 2;
   private static final int ZXING_STORAGE_PERMISSION = 3;

   private Class<?> mClss;
   /*主订单号*/
   EditText mEtMainOrder;
   /*添加item*/
   Button mBtAdd;
   /*添加清除所有*/
   Button mBtClear;
   /*扫描*/
   Button mBtScan;
   /*导出数据*/
   Button mBtExport;

   EditText mEtCurrentSelect;

   List<BarCodeInfo> mListInfo;

   RecyclerView mRecycleView;

   PackageIoAdapter mPackageIoAdapter;

   BarCodeDao mBarCodeDao;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      initView();
      mListInfo = new ArrayList<>();
      mEtCurrentSelect= mEtMainOrder;
      mBarCodeDao = new BarCodeDao();
   }

   private void initView(){
      mEtMainOrder = findViewById(R.id.et_package_mainordernum);
      //mLinearLayout = findViewById(R.id.ll_package_itemorder);
      mBtAdd = findViewById(R.id.bt_package_additem);
      mBtAdd.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            addItem();
         }
      });
      mBtClear = findViewById(R.id.bt_package_cleardata);
      mRecycleView = findViewById(R.id.recycleview_packageio);
      mBtClear.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            String boxCode = mEtMainOrder.getText().toString().trim();
            if(mListInfo!=null&&!TextUtils.isEmpty(boxCode)){
               clearRemote(boxCode);
               mListInfo.clear();
               if(mPackageIoAdapter!=null){
                  mPackageIoAdapter.updateAdapter(mListInfo);
               }
            }


         }
      });
      mBtScan = findViewById(R.id.bt_package_scan);
      mBtScan.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            openScan();
         }
      });
      mBtExport = findViewById(R.id.bt_package_exportdata);
      mBtExport.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            exportData();
         }
      });

      mEtMainOrder.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View view, boolean b) {
            if(b&&mPackageIoAdapter!=null){
               mPackageIoAdapter.setmCurrentFourcePosition(-1);
            }
         }
      });
   }

   private void clearRemote(final String boxNo){
      final NiftyDialogComponents mDialog = new NiftyDialogComponents(this);
      mDialog.setUpNifty("取消","确认","提示","确认删除所有此包装信息");
      mDialog.setNoftyCallBack(new NiftyDialogComponents.OnNiftyCallBack() {
         @Override
         public void onBt1Click() {
            mDialog.dismissBuilder();
         }

         @Override
         public void onBt2Click() {

            mDialog.dismissBuilder();
            mBarCodeDao.delBaseBoxCode(boxNo);
         }
      });
      mDialog.showBuilder();
   }

   private void addItem(){

      String boxCode = mEtMainOrder.getText().toString().trim();

      if(TextUtils.isEmpty(boxCode)){
         showShort("请先输入主包条码");
         return;
      }

      if(mListInfo==null){
         mListInfo = new ArrayList<>();
      }

      BarCodeInfo mBarCodeInfo =  new BarCodeInfo();
      mBarCodeInfo.setBoxNo(boxCode);
      if(mPackageIoAdapter==null){
         mListInfo.add(mBarCodeInfo);
         initAdapter();
      }else{
         mPackageIoAdapter.addData(mBarCodeInfo);
      }
   }


   private void initAdapter(){
      mPackageIoAdapter = new PackageIoAdapter(this,mListInfo);
      mPackageIoAdapter.setPackageListener(this);
      mRecycleView.setLayoutManager(new LinearLayoutManager(this));
      mRecycleView.setAdapter(mPackageIoAdapter);
   }

   private void openScan(){
      launchActivity(ScanActivity.class);
   }

   private void exportData(){
      String boxCode = mEtMainOrder.getText().toString().trim();

      if(TextUtils.isEmpty(boxCode)||mListInfo.size()==0){
         showShort("请先录入数据");
         return;
      }
      if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this,
               new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ZXING_STORAGE_PERMISSION);
      } else {
         saveExcel(boxCode);
      }
   }


   private  String getSDPath() {
      File sdDir = null;
      boolean sdCardExist = Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED);
      if (sdCardExist) {
         sdDir = Environment.getExternalStorageDirectory();
      }
      String dir = sdDir.toString();
      return dir;
   }

   public  void makeDir(File dir) {
      if (!dir.getParentFile().exists()) {
         makeDir(dir.getParentFile());
      }
      dir.mkdir();
   }

   String [] titles = new String[]{"子单号","集包时间"};

   private void saveExcel(String boxCode){
        File file = new File(getSDPath() + "/dfwl");

       makeDir(file);
       ExcelUtils.initExcel(file.toString() + "/"+boxCode+".xls", titles,boxCode);
       String fileName = getSDPath() + "/dfwl/"+boxCode+".xls";
       ExcelUtils.writeObjListToExcel(getRecordData(), fileName, this);
       updateExportStatus(boxCode);
       showLong("文件保存在"+fileName);
   }


   /**
    * 将数据集合 转化成ArrayList<ArrayList<String>>
    * @return
    */
   private  ArrayList<ArrayList<String>> getRecordData() {
      ArrayList<ArrayList<String>> recordList= new ArrayList<>();
      for (int i = 0; i <mListInfo.size(); i++) {
         BarCodeInfo mBarCodeInfo = mListInfo.get(i);
         ArrayList<String> beanList = new ArrayList<String>();
         beanList.add(mBarCodeInfo.getExpressCode());
         beanList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mBarCodeInfo.getEnterDate()));
         recordList.add(beanList);
      }
      return recordList;
   }


   public void launchActivity(Class<?> clss) {
      if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
         mClss = clss;
         ActivityCompat.requestPermissions(this,
               new String[]{Manifest.permission.CAMERA}, ZXING_CAMERA_PERMISSION);
      } else {
         Intent intent = new Intent(this, clss);
         startActivityForResult(intent,ZXING_CAMERA_REQUESTCODE);
      }
   }

   @Override
   public void onRequestPermissionsResult(int requestCode,  String permissions[], int[] grantResults) {
      switch (requestCode) {
         case ZXING_CAMERA_PERMISSION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               if(mClss != null) {
                  Intent intent = new Intent(this, mClss);
                  startActivityForResult(intent,ZXING_CAMERA_REQUESTCODE);
               }
            } else {
               showShort("需要相机权限");
            }
            return;
         case ZXING_STORAGE_PERMISSION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               exportData();
            } else {
               showShort("需要存储权限");
            }
            return;
      }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if(requestCode==ZXING_CAMERA_REQUESTCODE&&resultCode== Activity.RESULT_OK){
         String content = data.getStringExtra("content");

         if(mPackageIoAdapter==null||mPackageIoAdapter.getmCurrentFourcePosition()==-1){
            mEtMainOrder.setText(content);
            getBarCodeInfoBaseMainId(content);

         }else{
            int position = mPackageIoAdapter.getmCurrentFourcePosition();
            mPackageIoAdapter.getData(position).setExpressCode(content);
            mPackageIoAdapter.notifyItemChanged(position);
         }
      }
   }

   @Override
   public void onClickSave(int position,String barcode) {

      String mainOrderCode = mEtMainOrder.getText().toString();
      if(TextUtils.isEmpty(mainOrderCode)){
         Toast.makeText(this,"请先输入主包的单号",Toast.LENGTH_SHORT).show();
         return ;
      }

      if(TextUtils.isEmpty(barcode)){
         Toast.makeText(this,"请输入单号",Toast.LENGTH_SHORT).show();
         return ;
      }
      BarCodeInfo mBarCodeInfo =  mPackageIoAdapter.getData(position);
      mBarCodeInfo.setBoxNo(mainOrderCode);
      mBarCodeInfo.setExpressCode(barcode);
      mBarCodeInfo.setEnterDate(new Date());
      mBarCodeInfo.setSaved(false);

      mPackageIoAdapter.notifyItemChanged(position);

      mBarCodeDao.saveData(mBarCodeInfo);

   }

   @Override
   public void onClickDel(final int position) {

      final NiftyDialogComponents mDialog = new NiftyDialogComponents(this);
      int positionSize = position+1;
      mDialog.setUpNifty("取消","确认","提示","确认删除第"+positionSize+"个条码");
      mDialog.setNoftyCallBack(new NiftyDialogComponents.OnNiftyCallBack() {
         @Override
         public void onBt1Click() {
            mDialog.dismissBuilder();
         }

         @Override
         public void onBt2Click() {

            BarCodeInfo mBarCodeInfo =  mPackageIoAdapter.getData(position);
            mPackageIoAdapter.removeData(position);
            mDialog.dismissBuilder();

            mBarCodeDao.delBaseExpressCode(mBarCodeInfo.getExpressCode());
         }
      });
      mDialog.showBuilder();
   }


   private  void  getBarCodeInfoBaseMainId(String boxNo){
      String sql = "select * from PACKINGIO where BOX_NO= '"+boxNo +"' and UPLOAD = 0";
      List<BarCodeInfo>  mList = mBarCodeDao.selectDataFromDb(sql);
      if(mList!=null){
         mListInfo.clear();
         mListInfo.addAll(mList);
         initAdapter();
      }
   }

   private void updateExportStatus(String boxNo){
      String sql = "update  from PACKINGIO set UPLOAD = 1 where BOX_NO= '"+boxNo +"' ";
      mBarCodeDao.updateDataFromDb(sql);
      mListInfo.clear();
      if(mPackageIoAdapter!=null){
         mPackageIoAdapter.updateAdapter(mListInfo);
      }
   }


}
